import 'package:flutter/material.dart';

abstract class KeyboardUtil {
  /// 收起键盘
  static void closeKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);

    /// 键盘是否是弹起状态
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }
}

/// 扩展widget，方便使用
extension KeyboardUtilExtension on Widget {
  /// 收起键盘 - 点击和滑动
  Widget closeKeyboard(BuildContext context) {
    return GestureDetector(
      onTap: () => KeyboardUtil.closeKeyboard(context),
      onPanDown: (_) => KeyboardUtil.closeKeyboard(context),
      child: this,
    );
  }

  /// 收起键盘 - 点击
  Widget closeKeyboardOnTap(BuildContext context) {
    return GestureDetector(
      onTap: () => KeyboardUtil.closeKeyboard(context),
      child: this,
    );
  }

  /// 收起键盘 - 滑动
  Widget closeKeyboardOnScroll(BuildContext context) {
    return GestureDetector(
      onPanDown: (_) => KeyboardUtil.closeKeyboard(context),
      child: this,
    );
  }
}
